from behave import *

from server.app.cloud_ide.schema.users.request.user_create_request import UserCreateRequest
from server.app.cloud_ide.schema.users.request.user_role_update_request import UserRoleUpdateRequest
from server.app.cloud_ide.schema.users.request.user_update_password_request import UserUpdatePassWordRequest
from server.app.cloud_ide.schema.users.request.user_update_request import UserUpdateRequest
from server.app.cloud_ide.service.role_service import RoleService
from server.app.cloud_ide.service.tenant_service import TenantService
from server.app.cloud_ide.service.user_service import UserService
from server.framework.core.logger import logger

user_service = UserService()
tenant_service = TenantService()
role_service = RoleService()


@step('将用户[{user_name}]加入租户[{tenant_name}]下的[{role_name}]角色中')
def 将用户_加入租户_下的_角色中(context, user_name, tenant_name, role_name):
    tenants = tenant_service.list_tenant()
    tenant_info = next((x for x in tenants if x.name == tenant_name), None)

    roles = role_service.get_role_list(tenant_id=tenant_info.id)
    role_info = next((x for x in roles if x.name == role_name), None)

    users = user_service.list_users()
    target_user = next((x for x in users if x.username == user_name), None)
    rs = user_service.set_user_roles(UserRoleUpdateRequest(
        id=target_user.id,
        group_id=role_info.id
    ))
    assert rs


@given('用户列表没有如下测试用户')
def 用户列表没有如下测试用户(context):
    users = user_service.list_users()
    user_names = [x['username'] for x in context.table]
    target_user_ids = [x.id for x in users if x.username in user_names]
    rs = user_service.delete_users(target_user_ids)
    assert rs


@step("查看用户详情列表")
def get_user_list(context):
    try:
        users = user_service.list_users()
        logger.info(users)
        assert True
    except Exception as e:
        assert False, e


@step('管理员修改用户[{username}]的密码为[{new_password}]')
def step_impl(context, username, new_password):
    users = user_service.list_users()
    target_user = next((x for x in users if x.username == username), None)
    rs = user_service.change_password(UserUpdatePassWordRequest(
        id=target_user.id,
        new_password=new_password,
        need_renew=True,
        operator_is_admin=True
    ))
    assert rs


@step('[{username}]用户输入旧密码[{old_password}]并修改密码为[{new_password}]')
def step_impl(context, username, old_password, new_password):
    users = user_service.list_users()
    target_user = next((x for x in users if x.username == username), None)
    rs = user_service.change_password(UserUpdatePassWordRequest(
        id=target_user.id,
        password=old_password,
        new_password=new_password,
        need_renew=True,
        operator_is_admin=False
    ))
    assert rs


@step("新增用户,信息如下")
def 新增用户_信息如下(context):
    try:
        for row in context.table:
            create_user_request = UserCreateRequest(
                username=row['username'],
                email=row['email'],
                first_name=row['firstName'],
                last_name=row['lastName'],
                password=row['password']
            )
            user_service.create_user(create_user_request)
        assert True
    except Exception as e:
        assert False, e


@step('查询用户详情列表，以下用户成功新增')
def 查询用户详情列表_以下用户成功新增(context):
    try:
        users = user_service.list_users()
        for row in context.table:
            target_user = None
            for user in users:
                if row['username'] == user.username:
                    target_user = user
            assert target_user is not None
    except Exception as e:
        assert False, e


@then('用户[{username}]的信息被修改为')
def 用户__的信息被修改为(context, username):
    users = user_service.list_users()
    target_user = next((x for x in users if x.username == username), None)
    assert target_user is not None
    row = list(context.table)[0]
    if target_user.email != row['email'] or target_user.email != row[
        'email'] or target_user.email != row['email'] or target_user.email != row['email']:
        assert False
    else:
        assert True


@step('删除以下用户')
def 删除以下用户(context):
    users = user_service.list_users()
    user_names = [x['username'] for x in context.table]
    target_user_ids = [str(x.id) for x in users if x.username in user_names]
    rs = user_service.delete_users(target_user_ids)
    assert rs


@then('查询用户列表，用户列表不包含以下用户信息')
def 查询用户列表_用户列表不包含以下用户信息(context):
    users = user_service.list_users()
    user_names = [x['username'] for x in context.table]
    target_user_ids = [x.id for x in users if x.username in user_names]
    assert len(target_user_ids) == 0


@step('编辑用户[{username}]的详情信息,将用户信息修改为')
def 编辑用户__的详情信息_将用户信息修改为(context, username):
    users = user_service.list_users()
    target_user = next((x for x in users if x.username == username), None)
    user_detail = user_service.get_user_detail(target_user.id)
    update_user_request = UserUpdateRequest(
        id=user_detail.id,
        email=context.table[0]['email'],
        first_name=context.table[0]['firstName'],
        last_name=context.table[0]['lastName']
    )
    rs = user_service.update_user_info(update_user_request)
    assert rs


@step('查看用户[{username}]的详情信息')
def 查看用户__的详情信息(context, username):
    users = user_service.list_users()
    target_user = next((x for x in users if x.username == username), None)
    logger.info(target_user)
    assert target_user is not None

#
#
# @then("验证返回的搜索结果标题为{result}")
# def step_impl(context, result):
#     logger.info(f'验证返回的搜索结果标题为{result}')
